package com.wms.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.wms.entity.WUser;
import com.wms.service.WUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 验证请求头token
 * @author li xiaoYu
 */
@Component
public class JwtInterceptor extends InterceptorRegistry implements HandlerInterceptor {
    @Autowired
    private WUserService userService;


    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object object) throws Exception {

        //获取token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        // 执行认证,token不存在
        if (StrUtil.isBlank(token)) {
            httpServletResponse.setStatus(202);
            httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write("{\n" +
                    "    \"data\": null,\n" +
                    "    \"code\": 401,\n" +
                    "    \"msg\": \"没有token，重新登陆\"\n" +
                    "}");
            return false;
        }

        //获取token的userid
        String username;
        try {
            //解密获取
            username = JWT.decode(token).getAudience().get(0); //得到token中的userid载荷
        } catch (JWTDecodeException j) {

            httpServletResponse.setStatus(202);
            httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write("{\n" +
                    "    \"data\": null,\n" +
                    "    \"code\": 401,\n" +
                    "    \"msg\": \"token验证失败，重新登陆\"\n" +
                    "}");
            return false;
        }

        //根据userid查询数据库
        WUser user = userService.queryByUserName(username);

        if (user == null) {
            httpServletResponse.setStatus(202);
            httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write("{\n" +
                    "    \"data\": null,\n" +
                    "    \"code\": 401,\n" +
                    "    \"msg\": \"token验证失败，重新登陆\"\n" +
                    "}");
            return false;
        }

        // 用户密码加签验证 token
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//        try {
//            jwtVerifier.verify(token);
//        } catch (JWTVerificationException e) {
//            throw new ServiceException(Constants.CODE_401,"token验证失败，重新登陆");
//        }

        return true;
    }
}